<template>
  <view class="container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <u-icon name="search" size="20" color="#999"></u-icon>
        <input 
          type="text" 
          placeholder="搜索公司..." 
          v-model="searchQuery"
          @input="handleSearch"
          class="search-text"
        />
      </view>
    </view>
    
    <!-- 类目筛选 -->
    <view class="category-filter">
      <scroll-view scroll-x="true" class="category-scroll" show-scrollbar="false">
        <view 
          class="category-item" 
          :class="{ active: currentCategory === 'all' }"
          @click="currentCategory = 'all'"
        >
          全部
        </view>
        <view 
          class="category-item" 
          :class="{ active: currentCategory === category.id }"
          @click="currentCategory = category.id"
          v-for="category in categories" 
          :key="category.id"
        >
          {{ category.name }}
        </view>
      </scroll-view>
    </view>
    
    <!-- 排名列表 -->
    <view class="ranking-list">
      <view class="list-header">
        <text class="header-text">公司排名</text>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoading && !companies.length">
        <u-loading-icon mode="circle" :size="24" color="#409eff"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 错误状态 -->
      <view class="error-state" v-else-if="error && !companies.length">
        <u-icon name="error-circle" size="60" color="#ff4d4f" class="error-icon"></u-icon>
        <text class="error-text">{{ error }}</text>
        <button class="retry-btn" @click="fetchData">
          <text>重新加载</text>
        </button>
      </view>
      
      <!-- 公司列表 -->
      <view v-else-if="processedCompanies&&processedCompanies.length > 0">
        <view 
          class="company-item" 
          :class="item.rankClass"
          @click="navigateToDetail(item)"
          v-for="(item, index) in processedCompanies" 
          :key="item.id"
        >
          <!-- 排名 -->
          <view class="rank-number">
            {{ item.rank }}
          </view>
          
          <!-- 公司信息 -->
          <view class="company-info">
            <image :src="item.logo" class="company-logo" mode="aspectFill"></image>
            <view class="company-details">
              <view class="company-header">
                <text class="company-name">{{ item.name }}</text>
                <view class="company-category" :class="'category-' + item.category">
                  <text class="category-text">{{ getCategoryName(item.category) }}</text>
                </view>
              </view>
              <text class="company-desc">{{ item.description }}</text>
            </view>
          </view>
          
          <!-- 商品数量 -->
          <!-- <view class="product-count">
            <u-icon name="list" size="16" color="#999"></u-icon>
            <text class="product-count-text">{{ item.products }}</text>
          </view> -->
          
          <!-- 箭头 -->
          <view class="arrow-icon">
            <u-icon name="arrow-right" size="20" color="#ccc"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!isLoading && !error">
        <u-icon name="search" size="80" color="#ddd" class="empty-icon"></u-icon>
        <text class="empty-text">未找到相关公司</text>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && !isLoading">
        <button class="load-more-btn" @click="loadMore">
          <text>加载更多</text>
        </button>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-else-if="!hasMore && companies.length > 0 && !isLoading">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      currentCategory: 'all',
      categories: [], // 从接口获取
      companies: [], // 分页数据
      allCompanies: [], // 所有数据（用于搜索）
      isLoading: false,
      isLoadMore: false,
      error: null,
      page: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    };
  },
  
  computed: {
    // 处理后的公司列表，包含排名样式类
    processedCompanies() {
	 if(this.allCompanies&&this.allCompanies.length==0){
		 return 
	 }
      // 先筛选公司
      let filtered = this.allCompanies.filter(company => {
        const categoryMatch = this.currentCategory === 'all' || company.category === this.currentCategory;
        const searchMatch = !this.searchQuery || 
          company.name.includes(this.searchQuery) || 
          company.description.includes(this.searchQuery) ||
          company.products.some(product => product.name.includes(this.searchQuery));
          
        return categoryMatch && searchMatch;
      });
      
      // 为每个公司添加排名样式类
      return filtered.map(company => {
        let rankClass = '';
        if (company.rank === 1) rankClass = 'rank-first';
        else if (company.rank === 2) rankClass = 'rank-second';
        else if (company.rank === 3) rankClass = 'rank-third';
        
        return {
          ...company,
          rankClass
        };
      });
    }
  },
  
  onLoad() {
    // 页面加载时获取数据
    this.fetchCategories();
    this.fetchCompanies();
  },
  
  methods: {
    // 获取分类数据
    async fetchCategories() {
      try {
        const response = await this.$request('api/v1/classList', 'GET');
        if (response.code === 200) {
          this.categories = response.data;
        } else {
          console.error('获取分类失败:', response.msg);
          this.categories = [];
        }
      } catch (error) {
        console.error('获取分类失败:', error);
        this.error = '分类数据加载失败';
      }
    },
    
    // 获取公司数据（分页）
    async fetchCompanies(reset = true) {
      if (reset) {
        this.page = 1;
        this.companies = [];
        this.allCompanies = [];
        this.isLoading = true;
      } else {
        this.isLoadMore = true;
      }
      
      this.error = null;
      
      try {
        const params = {
          pageNum: this.page,
          pageSize: this.pageSize,
          category: this.currentCategory !== 'all' ? this.currentCategory : '',
          name: this.searchQuery || ''
        };
        
        const response = await this.$request('api/v1/companies/ranking', 'GET', params);
        if (response.code === 200) {
          const data = response.rows;
          this.total = response.total;
          this.hasMore = data.length === this.pageSize;
          
          if (reset) {
            this.companies = data;
          } else {
            this.companies = [...this.companies, ...data];
          }
          
          // 更新所有数据
          this.allCompanies = [...this.companies];
        } else {
          console.error('获取公司数据失败:', response.msg);
          if (reset) {
            this.companies = [];
            this.allCompanies = [];
          }
        }
      } catch (error) {
        console.error('获取公司数据失败:', error);
        this.error = '公司数据加载失败，请检查网络连接';
        if (reset) {
          this.companies = [];
          this.allCompanies = [];
        }
      } finally {
        this.isLoading = false;
        this.isLoadMore = false;
      }
    },
    
    // 获取所有数据
    async fetchData() {
      this.page = 1;
      this.companies = [];
      this.allCompanies = [];
      this.isLoading = true;
      this.error = null;
      
      try {
        // 并行获取分类和公司数据
        await Promise.all([
          this.fetchCategories(),
          this.fetchCompanies(true)
        ]);
      } catch (error) {
        console.error('获取数据失败:', error);
        this.error = '数据加载失败，请检查网络连接';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 加载更多
    loadMore() {
      if (!this.hasMore || this.isLoading || this.isLoadMore) return;
      
      this.page++;
      this.fetchCompanies(false);
	  this.isLoading = false;
    },
    
    // 搜索处理
    handleSearch() {
      // 搜索时重置分页
      this.fetchCompanies(true);
	  this.isLoading = false;
    },
    
    // 分类筛选处理
    onCategoryChange(categoryId) {
      this.currentCategory = categoryId;
      this.fetchCompanies(true);
	  this.isLoading = false;
    },
    
    // 根据类别ID获取类别名称
    getCategoryName(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId);
      return category ? category.name : '未知';
    },
    
    // 跳转到详情页
    navigateToDetail(company) {
		const com = company
		com.categoryName = this.getCategoryName(company.category)
      // 保存当前公司信息到全局
      getApp().globalData.currentCompany = com;
      uni.navigateTo({
        url: `/pages/ranking/rankingDetail`
      });
	  this.isLoading = false;
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #f5f5f5 100%);
  padding-top: 10px;
}

/* 搜索栏样式 */
.search-bar {
  padding: 0 16px 10px;
  background: transparent;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 24px;
  padding: 12px  16px;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.search-text {
  flex: 1;
  margin-left: 10px;
  font-size: 14px;
  color: #333;
  background-color: transparent;
}

/* 类目筛选样式 */
.category-filter {
  background-color: #ffffff;
  padding: 10px 0;
  margin: 0 16px;
  border-radius: 16px;
  box-shadow: 0 rpx 12rpx rgba(0, 0, 0, 0.05);
}

.category-scroll {
  white-space: nowrap;
  padding: 0 0px;
}

.category-item {
  display: inline-block;
  padding: 8px 18px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  background-color: #f8f9fa;
  transition: all 0.3s ease;
}

.category-item.active {
  background-color: #409eff;
  color: #ffffff;
  transform: scale(1.05);
}

/* 排名列表样式 */
.ranking-list {
  flex: 1;
  padding: 10px 0;
}

.list-header {
  padding: 0 16px 16px;
}

.header-text {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.header-text::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #409eff, #1890ff);
  border-radius: 2px;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  gap: 15px;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

/* 错误状态样式 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  gap: 15px;
}

.error-icon {
  margin-bottom: 10px;
}

.error-text {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 20px;
  text-align: center;
}

.retry-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 10px 24px;
  font-size: 14px;
}

/* 加载更多样式 */
.load-more {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.load-more-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 10px 24px;
  font-size: 14px;
}

/* 没有更多数据样式 */
.no-more {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.no-more-text {
  color: #999;
  font-size: 14px;
}

/* 公司项样式 */
.company-item {
  display: flex;
  align-items: center;
  padding: 18px;
  margin: 0 16px 12px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.company-item::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(135deg, #409eff, #1890ff);
  border-radius: 0 16px 16px 0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.company-item:hover,
.company-item:active {
  transform: translateY(-2px);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
}

.company-item:hover::after,
.company-item:active::after {
  opacity: 1;
}

/* 前三名特殊样式 */
.company-item.rank-first .rank-number {
  background: linear-gradient(135deg, #ffd700, #ffa500);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(255, 215, 0, 0.4);
}

.company-item.rank-second .rank-number {
  background: linear-gradient(135deg, #c0c0c0, #a9a9a9);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(192, 192, 192, 0.4);
}

.company-item.rank-third .rank-number {
  background: linear-gradient(135deg, #cd7f32, #b87333);
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(205, 127, 50, 0.4);
}

/* 排名数字样式 */
.rank-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f2f5;
  color: #666;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

/* 公司信息样式 */
.company-info {
  flex: 1;
  display: flex;
  align-items: flex-start;
  min-width: 0; /* 关键：允许内容收缩 */
}

.company-logo {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  margin-right: 16px;
  flex-shrink: 0;
  border: 2px solid #f0f2f5;
  box-sizing: border-box;
}

.company-details {
  flex: 1;
  overflow: hidden;
  min-width: 0; /* 关键：允许内容收缩 */
}

.company-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-right: 10px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.company-category {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  flex-shrink: 0;
}

.category-tech {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.category-finance {
  background-color: #f9f0ff;
  color: #722ed1;
  border: 1px solid #d3adf7;
}

.category-retail {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.category-healthcare {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.category-education {
  background-color: #f0f5ff;
  color: #177ddc;
  border: 1px solid #85a5ff;
}

.company-desc {
  font-size: 13px;
  color: #666;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
  max-width: 100%; /* 确保不超过容器宽度 */
}

/* 商品数量样式 */
.product-count {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  padding: 4px 8px;
  background-color: #f8f9fa;
  border-radius: 12px;
  flex-shrink: 0;
}

.product-count-text {
  font-size: 13px;
  color: #666;
  margin-left: 4px;
}

/* 箭头图标 */
.arrow-icon {
  color: #ccc;
  flex-shrink: 0;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80px 0;
  text-align: center;
}

.empty-icon {
  margin-bottom: 20px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .container {
    padding-top: 5px;
  }
  
  .search-input {
    padding: 10px 14px;
  }
  
  .search-text {
    font-size: 13px;
  }
  
  .category-item {
    padding: 6px 14px;
    font-size: 13px;
  }
  
  .company-item {
    padding: 15px;
  }
  
  .company-logo {
    width: 45px;
    height: 45px;
  }
  
  .company-name {
    font-size: 15px;
  }
  
  .company-category {
    font-size: 11px;
    padding: 3px 8px;
  }
  
  .company-desc {
    font-size: 12px;
  }
  
  .product-count {
    padding: 3px 6px;
  }
  
  .product-count-text {
    font-size: 12px;
  }
}
</style>



